const Service = require('egg').Service;

class AccountService extends Service {
  constructor(ctx) {
    super(ctx);
    this.model = ctx.model.Account;
  }

  async accountLogin(param) {
    const option = {
      where: {
        account_name: param.account_name
      }
    };
    try {
      const user = await this.model.findOne(option);
      if (user) {
         const userPwd = this.ctx.helper.parseCrypto(param.password)
         const pwd = this.ctx.helper.parseCrypto(user.password)
         if (userPwd === pwd) {
           return { data: user }
         }
      }
      return { error: '帐号或密码错误' };
    } catch (e) {
      return { error: e.message };
    }
  }

  async getAccountById(id) {
    const { ctx } = this;
    const prefix = `${ctx.helper.webSitePrefix}${ctx.helper.uploadImagePath}`;
    try {
      let result = await this.model.findOne({ where: { account_id: id }});
      result = result.get({ plain: true });
      if (result) {
        result.resource_prefix = prefix;
      }
      return { data: result };
    } catch (e) {
      return { error: e.message };
    }
  }

  async saveAccountById(param) {
    const row = {
      account_name: param.account_name,
      avatar: param.avatar,
      current_residence: param.current_residence,
      email: param.email,
      hometown: param.hometown,
      introduce: param.introduce,
      mobile: param.mobile,
      sex: param.sex,
      signature: param.signature,
      tencent_qq: param.tencent_qq,
    };
    const option = {
      where: { account_id: param.account_id },
    };
    try {
      return await this.model.update(row, option);
    } catch (e) {
      return { error: e.message };
    }
  }

  async updatePassword(param) {
    const { data: account } = await this.getAccountById(param.account_id);

    if (!account || account.password !== param.old_password) {
      return { error: '旧密码错误' };
    }

    const row = {
      password: param.new_password,
    };
    const option = {
      where: { account_id: param.account_id },
    };
    try {
      return await this.model.update(row, option);
    } catch (e) {
      return { error: e.message };
    }
  }
}

module.exports = AccountService;
